package test;

import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Scanner;

import library.DaoUtil;
import library.console.MainMenu;
import library.controller.*;
import library.entity.BookingRecord;

import org.junit.Before;
import org.junit.Test;

public class SystemTestConsole {
	private String command;
	private BorrowController borrow;
	private BookController book;
	private LibrarianController librarianController;
	private ReaderController readerController;
	
	final private String loginString = "admin\nadmin\n";
	final private String readerNameString = "testReader";
	
    TestData testData;
    
	@Before
	public void setUp() throws SQLException{
		DaoUtil.init();
		testData = new TestData();
		borrow = new BorrowController(testData.getTestReader());
		readerController = new ReaderController();
		librarianController = new LibrarianController();
	}
	
	//Borrow Menu Testing
	@Test
	public void borrow(){
		executeCommand("2\n1\n999\n-1\n","borrow");
		BookingRecord borrowBook = borrow.getBookingRecord().get(0);
		assertEquals(1,borrowBook.getBookID());
	}
	
	@Test
	public void returnBook(){
		borrow.borrowBook(1);
		executeCommand("5\n1\n2\n999\n-1\n","borrow");
		assertEquals(borrow.getBookingRecord().size(),0);
	}
	
	@Test
	public void showBookRecord(){
		borrow.borrowBook(1);
		executeCommand("1\n1\n\n","borrow");
	}
	
	@Test
	public void renewBookRecord(){
		borrow.borrowBook(1);
		executeCommand("4\nall\n\n","borrow");
		int reutrnDate = borrow.getBookingRecord().get(0).getReturnDate().get(Calendar.DAY_OF_YEAR);
		Calendar today = Calendar.getInstance();
		int todayInInt = today.get(Calendar.DAY_OF_YEAR);
		assertEquals(todayInInt+borrow.loanDate,reutrnDate);
	}
	
	//Administration Menu Testing
	@Test
	public void adminAddUser(){
		executeCommand("1\n1\nabc\naaac\nhk\n987\n\n7\n","admin");
		assertNotNull(readerController.getReader("abc"));
		readerController.delete("abc");
	}
	@Test
	public void cleanUp(){
		testData.returnAllBorrowRecord();
	}
	public void executeCommand(String cmd, String menuType){
		String enterMenuString, exitString;
		if(menuType == "borrow"){
			enterMenuString = "1\n" + readerNameString + "\n";
			exitString = "6\n4\n";
		} else if (menuType == "admin"){
			enterMenuString = "3\n";
			exitString = "3\n4\n";
		}
		else {
			enterMenuString = "";
			exitString = "";
		}
		
		command = loginString + enterMenuString + cmd + exitString;
		ByteArrayInputStream in = new ByteArrayInputStream(command.getBytes());
		System.setIn(in);
		try {
			MainMenu.main(null);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
